package zapx

import (
	"fmt"
	"gitee.com/sdynasty/clever/log"
	"go.uber.org/zap"
)

type Logger struct {
	log    *zap.Logger // zap ensure that zap.Logger is safe for concurrent use
	msgKey string
}
func (l *Logger) Log(level log.Level, keyvals ...interface{}) error {
	if len(keyvals) == 0 {
		return nil
	}
	if (len(keyvals) & 1) == 1 {
		keyvals = append(keyvals, "KEYVALS UNPAIRED")
	}
	var msg string
	fields := make([]zap.Field, 0)
	for i := 0; i < len(keyvals); i += 2 {
		k, v := keyvals[i], keyvals[i+1]
		key, ok := keyvals[i].(string)
		if ok {
			if key == l.msgKey {
				msg = fmt.Sprintf("%v", v)
			} else {
				fields = append(fields, zap.Any(key, v))
			}
		} else {
			fields = append(fields, zap.Any(fmt.Sprintf("%v", k), v))
		}
	}

	switch level {
	case log.LevelDebug:
		l.log.Debug(msg, fields...)
	case log.LevelInfo:
		l.log.Info(msg, fields...)
	case log.LevelWarn:
		l.log.Warn(msg, fields...)
	case log.LevelError:
		l.log.Error(msg, fields...)
	case log.LevelFatal:
		l.log.Fatal(msg, fields...)
	}
	return nil
}

func NewSugarLogger(z *zap.Logger, msgKey string) *Logger {
	l := &Logger{
		log:    z,
		msgKey: msgKey,
	}
	return l
}

func init() {
	z, _ := NewJSONLogger()

	logger := log.With(NewSugarLogger(z, log.DefaultMessageKey), "caller", log.Caller(4))
	log.SetLogger(logger)
}